const axios = require('axios');
const config = require('../../config/config');
const { setupLogger } = require('../../utils/logger');

class AveAiService {
  constructor() {
    this.logger = setupLogger();
    this.baseUrl = config.dataSources.aveAi.baseUrl;
    this.rateLimitRemaining = 100;
    this.rateLimitReset = Date.now();
  }

  async fetchData() {
    try {
      this.logger.info('开始获取Ave.ai数据...');
      
      // 检查速率限制
      if (this.rateLimitRemaining <= 0 && Date.now() < this.rateLimitReset) {
        this.logger.warn('Ave.ai API速率限制，跳过本次获取');
        return [];
      }

      const data = [];
      
      // 获取代币搜索结果
      const tokenSearch = await this.searchTokens();
      data.push(...tokenSearch);
      
      // 获取代币价格数据
      const tokenPrices = await this.getTokenPrices();
      data.push(...tokenPrices);
      
      // 获取排行榜数据
      const rankingData = await this.getRankingData();
      data.push(...rankingData);
      
      // 获取K线数据
      const klineData = await this.getKlineData();
      data.push(...klineData);
      
      // 获取链上数据分析
      const onChainData = await this.getOnChainAnalysis();
      data.push(...onChainData);
      
      this.logger.info(`Ave.ai数据获取完成，共获取 ${data.length} 条数据`);
      return data;
    } catch (error) {
      this.logger.error('Ave.ai数据获取失败:', error);
      return [];
    }
  }

  async searchTokens() {
    try {
      // Ave.ai代币搜索接口
      const response = await axios.get(`${this.baseUrl}/v2/token/search`, {
        params: {
          keyword: 'BTC,ETH,SOL',
          limit: 50
        },
        timeout: 10000
      });
      
      this.updateRateLimit();
      
      if (!response.data || !response.data.data) {
        return [];
      }
      
      return response.data.data.map(token => ({
        source: 'ave_ai',
        type: 'token_search',
        address: token.address,
        symbol: token.symbol,
        name: token.name,
        decimals: parseInt(token.decimals || 18),
        chainId: token.chain_id,
        chainName: token.chain_name,
        logoUrl: token.logo_url,
        price: parseFloat(token.price || 0),
        priceChange24h: parseFloat(token.price_change_24h || 0),
        volume24h: parseFloat(token.volume_24h || 0),
        marketCap: parseFloat(token.market_cap || 0),
        liquidity: parseFloat(token.liquidity || 0),
        holders: parseInt(token.holders || 0),
        isVerified: token.is_verified || false,
        riskLevel: token.risk_level || 'unknown',
        tags: token.tags || [],
        timestamp: new Date().toISOString()
      }));
    } catch (error) {
      this.logger.error('获取Ave.ai代币搜索失败:', error);
      return this.getMockTokenSearch();
    }
  }

  async getTokenPrices() {
    try {
      const response = await axios.get(`${this.baseUrl}/v2/token/prices`, {
        params: {
          addresses: 'ethereum:0xA0b86a33E6441b8435b662f0E2d0C8b7b5c7e8e8,solana:So11111111111111111111111111111111111111112',
          vs_currency: 'usd'
        },
        timeout: 10000
      });
      
      this.updateRateLimit();
      
      if (!response.data || !response.data.data) {
        return [];
      }
      
      return Object.entries(response.data.data).map(([address, priceData]) => ({
        source: 'ave_ai',
        type: 'token_price',
        address: address,
        price: parseFloat(priceData.price || 0),
        priceChange1h: parseFloat(priceData.price_change_1h || 0),
        priceChange24h: parseFloat(priceData.price_change_24h || 0),
        priceChange7d: parseFloat(priceData.price_change_7d || 0),
        volume24h: parseFloat(priceData.volume_24h || 0),
        marketCap: parseFloat(priceData.market_cap || 0),
        lastUpdated: priceData.last_updated,
        timestamp: new Date().toISOString()
      }));
    } catch (error) {
      this.logger.error('获取Ave.ai代币价格失败:', error);
      return this.getMockTokenPrices();
    }
  }

  async getRankingData() {
    try {
      const response = await axios.get(`${this.baseUrl}/v2/token/rank`, {
        params: {
          topic: 'trending',
          limit: 30,
          timeframe: '24h'
        },
        timeout: 10000
      });
      
      this.updateRateLimit();
      
      if (!response.data || !response.data.data) {
        return [];
      }
      
      return response.data.data.map((token, index) => ({
        source: 'ave_ai',
        type: 'ranking_data',
        rank: index + 1,
        address: token.address,
        symbol: token.symbol,
        name: token.name,
        chainId: token.chain_id,
        price: parseFloat(token.price || 0),
        priceChange24h: parseFloat(token.price_change_24h || 0),
        volume24h: parseFloat(token.volume_24h || 0),
        marketCap: parseFloat(token.market_cap || 0),
        score: parseFloat(token.score || 0),
        trendingScore: parseFloat(token.trending_score || 0),
        socialMentions: parseInt(token.social_mentions || 0),
        uniqueWallets24h: parseInt(token.unique_wallets_24h || 0),
        transactions24h: parseInt(token.transactions_24h || 0),
        timestamp: new Date().toISOString()
      }));
    } catch (error) {
      this.logger.error('获取Ave.ai排行榜数据失败:', error);
      return this.getMockRankingData();
    }
  }

  async getKlineData() {
    try {
      const response = await axios.get(`${this.baseUrl}/v2/token/kline`, {
        params: {
          pair: 'ethereum:0xA0b86a33E6441b8435b662f0E2d0C8b7b5c7e8e8_USDT',
          interval: '1h',
          limit: 100
        },
        timeout: 10000
      });
      
      this.updateRateLimit();
      
      if (!response.data || !response.data.data) {
        return [];
      }
      
      return response.data.data.map(kline => ({
        source: 'ave_ai',
        type: 'kline_data',
        pair: kline.pair,
        interval: kline.interval,
        timestamp: parseInt(kline.timestamp),
        open: parseFloat(kline.open),
        high: parseFloat(kline.high),
        low: parseFloat(kline.low),
        close: parseFloat(kline.close),
        volume: parseFloat(kline.volume),
        volumeUsd: parseFloat(kline.volume_usd || 0),
        trades: parseInt(kline.trades || 0),
        timestamp: new Date().toISOString()
      }));
    } catch (error) {
      this.logger.error('获取Ave.ai K线数据失败:', error);
      return [];
    }
  }

  async getOnChainAnalysis() {
    try {
      const response = await axios.get(`${this.baseUrl}/v2/analytics/onchain`, {
        params: {
          chain: 'ethereum,solana,bsc',
          metrics: 'dex_volume,unique_wallets,transactions',
          timeframe: '24h'
        },
        timeout: 10000
      });
      
      this.updateRateLimit();
      
      if (!response.data || !response.data.data) {
        return [];
      }
      
      return response.data.data.map(analysis => ({
        source: 'ave_ai',
        type: 'onchain_analysis',
        chainId: analysis.chain_id,
        chainName: analysis.chain_name,
        dexVolume24h: parseFloat(analysis.dex_volume_24h || 0),
        uniqueWallets24h: parseInt(analysis.unique_wallets_24h || 0),
        transactions24h: parseInt(analysis.transactions_24h || 0),
        activeTokens: parseInt(analysis.active_tokens || 0),
        newTokens24h: parseInt(analysis.new_tokens_24h || 0),
        topDexes: analysis.top_dexes || [],
        gasUsage: parseFloat(analysis.gas_usage || 0),
        avgGasPrice: parseFloat(analysis.avg_gas_price || 0),
        networkUtilization: parseFloat(analysis.network_utilization || 0),
        timestamp: new Date().toISOString()
      }));
    } catch (error) {
      this.logger.error('获取Ave.ai链上分析失败:', error);
      return this.getMockOnChainAnalysis();
    }
  }

  async getTokenDetail(address) {
    try {
      const response = await axios.get(`${this.baseUrl}/v2/token/detail`, {
        params: {
          address: address
        },
        timeout: 10000
      });
      
      this.updateRateLimit();
      
      if (!response.data || !response.data.data) {
        return null;
      }
      
      const token = response.data.data;
      return {
        source: 'ave_ai',
        type: 'token_detail',
        address: token.address,
        symbol: token.symbol,
        name: token.name,
        decimals: parseInt(token.decimals || 18),
        totalSupply: parseFloat(token.total_supply || 0),
        circulatingSupply: parseFloat(token.circulating_supply || 0),
        maxSupply: parseFloat(token.max_supply || 0),
        price: parseFloat(token.price || 0),
        marketCap: parseFloat(token.market_cap || 0),
        volume24h: parseFloat(token.volume_24h || 0),
        liquidity: parseFloat(token.liquidity || 0),
        holders: parseInt(token.holders || 0),
        contractVerified: token.contract_verified || false,
        auditStatus: token.audit_status || 'unknown',
        socialLinks: token.social_links || {},
        description: token.description || '',
        website: token.website || '',
        timestamp: new Date().toISOString()
      };
    } catch (error) {
      this.logger.error(`获取Ave.ai代币详情失败 ${address}:`, error);
      return null;
    }
  }

  // 模拟数据方法
  getMockTokenSearch() {
    return [
      {
        source: 'ave_ai',
        type: 'token_search',
        address: 'ethereum:0xA0b86a33E6441b8435b662f0E2d0C8b7b5c7e8e8',
        symbol: 'ETH',
        name: 'Ethereum',
        decimals: 18,
        chainId: 1,
        chainName: 'Ethereum',
        logoUrl: 'https://example.com/eth-logo.png',
        price: 2500.00,
        priceChange24h: 3.5,
        volume24h: 15000000,
        marketCap: 300000000000,
        liquidity: 5000000,
        holders: 100000000,
        isVerified: true,
        riskLevel: 'low',
        tags: ['defi', 'smart-contracts'],
        timestamp: new Date().toISOString()
      }
    ];
  }

  getMockTokenPrices() {
    return [
      {
        source: 'ave_ai',
        type: 'token_price',
        address: 'ethereum:0xA0b86a33E6441b8435b662f0E2d0C8b7b5c7e8e8',
        price: 2500.00,
        priceChange1h: 0.5,
        priceChange24h: 3.5,
        priceChange7d: 8.2,
        volume24h: 15000000,
        marketCap: 300000000000,
        lastUpdated: new Date().toISOString(),
        timestamp: new Date().toISOString()
      }
    ];
  }

  getMockRankingData() {
    return [
      {
        source: 'ave_ai',
        type: 'ranking_data',
        rank: 1,
        address: 'ethereum:0xA0b86a33E6441b8435b662f0E2d0C8b7b5c7e8e8',
        symbol: 'ETH',
        name: 'Ethereum',
        chainId: 1,
        price: 2500.00,
        priceChange24h: 3.5,
        volume24h: 15000000,
        marketCap: 300000000000,
        score: 95.5,
        trendingScore: 88.2,
        socialMentions: 5000,
        uniqueWallets24h: 50000,
        transactions24h: 1200000,
        timestamp: new Date().toISOString()
      }
    ];
  }

  getMockOnChainAnalysis() {
    return [
      {
        source: 'ave_ai',
        type: 'onchain_analysis',
        chainId: 1,
        chainName: 'Ethereum',
        dexVolume24h: 2500000000,
        uniqueWallets24h: 150000,
        transactions24h: 1200000,
        activeTokens: 5000,
        newTokens24h: 50,
        topDexes: ['Uniswap', 'SushiSwap', 'Curve'],
        gasUsage: 15000000,
        avgGasPrice: 25.5,
        networkUtilization: 0.85,
        timestamp: new Date().toISOString()
      }
    ];
  }

  updateRateLimit() {
    this.rateLimitRemaining = Math.max(0, this.rateLimitRemaining - 1);
    if (this.rateLimitRemaining === 0) {
      this.rateLimitReset = Date.now() + 60 * 1000; // 1分钟后重置
    }
  }

  delay(ms) {
    return new Promise(resolve => setTimeout(resolve, ms));
  }

  getRateLimitStatus() {
    return {
      remaining: this.rateLimitRemaining,
      resetTime: new Date(this.rateLimitReset).toISOString()
    };
  }
}

module.exports = new AveAiService();

